<template>
  <view class="container">
    <!-- 订单状态筛选 -->
    <view class="filter-tabs">
      <text
        v-for="(tab, index) in filterTabs"
        :key="index"
        class="filter-tab"
        :class="{ active: currentTab === index }"
        @click="switchTab(index)"
      >
        {{ tab }}
      </text>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view v-for="(order, index) in filteredOrders" :key="index" class="order-item" @click="viewOrderDetail(order)">
        <view class="order-header">
          <view class="order-info">
            <text class="order-no">订单编号：{{ order.orderNumber }}</text>
            <text class="order-time">{{ order.createTime }}</text>
          </view>
          <uni-tag :text="getStatusText(order)" :type="getStatusType(order.orderStatus)" size="small" />
        </view>

        <!-- 商品列表 -->
        <view class="order-products">
          <view
            v-for="(product, pIndex) in order.orderItems"
            :key="pIndex"
            class="order-content"
            :class="{ 'not-last': pIndex < order.orderItems.length - 1 }"
          >
            <image class="product-image" :src="product.mainImageUrl || '/static/default-product.png'" mode="aspectFill" />
            <view class="product-info">
              <text class="product-name">{{ product.productName }}</text>
              <text class="product-spec" v-if="product.attrValue">规格：{{ product.attrValue }}</text>
              <view class="price-quantity">
                <text class="price">¥{{ (product.sellingPrice / 100).toFixed(2) }}</text>
                <text class="quantity">x{{ product.productNum }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="order-footer">
          <text class="total">订单总计：¥{{ (order.sellingPrice / 100).toFixed(2) }}</text>
          <view class="actions">
            <button v-if="order.orderStatus === 1" class="action-btn edit" @click.stop="editOrder(order)">
              完善信息
            </button>
            <!-- <button
              v-if="order.orderStatus === 1 || order.orderStatus === 10"
              class="action-btn cancel"
              @click.stop="cancelOrder(order)"
            >
              取消订单
            </button> -->
            <!-- <button
              v-if="order.orderStatus === 20"
              class="action-btn confirm"
              @click.stop="confirmReceive(order)"
            >
              确认收货
            </button>
            <button
              v-if="order.orderStatus === 60"
              class="action-btn review"
              @click.stop="reviewOrder(order)"
            >
              评价
            </button> -->
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && orders.length === 0" class="loading-state">
      <uni-load-more
        status="loading"
        content-text="{ contentText: { contentdown: '上拉显示更多', contentrefresh: '正在加载...', contentnomore: '没有更多数据了' } }"
      ></uni-load-more>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && !refreshing && filteredOrders.length === 0" class="empty-state">
      <image class="empty-icon" src="/static/icons/empty.png" mode="aspectFit" />
      <text class="empty-text">暂无订单</text>
    </view>

    <!-- 底部加载更多状态 -->
    <view v-if="orders.length > 0" class="load-more-container">
      <uni-load-more
        v-if="loading"
        status="loading"
        content-text="{ contentText: { contentdown: '上拉显示更多', contentrefresh: '正在加载...', contentnomore: '没有更多数据了' } }"
      ></uni-load-more>
      <view v-else-if="allDataLoaded" class="all-loaded">
        <text class="all-loaded-text">已全部加载完成</text>
      </view>
      <view v-else-if="!hasMore" class="no-more">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </view>

    <!-- 编辑订单信息弹窗 -->
    <uni-popup ref="editPopup" type="center" :safe-area="false" background-color="rgba(0,0,0,0.5)">
      <view class="edit-modal">
        <view class="modal-header">
          <text class="modal-title">完善订单信息</text>
          <text class="close-btn" @click="closeEditModal">×</text>
        </view>
        <view class="modal-body">
          <uni-forms ref="editFormRef" :model="editForm" :rules="formRules" label-position="left" label-width="150rpx">
            <uni-forms-item label="联系人" name="contactName" required validate-trigger="blur">
              <uni-easyinput
                v-model="editForm.contactName"
                placeholder="请输入联系人姓名"
                type="text"
                :clearable="false"
                @blur="validateField('contactName')"
              />
            </uni-forms-item>
            <uni-forms-item label="手机号" name="contactPhone" required validate-trigger="blur">
              <uni-easyinput
                v-model="editForm.contactPhone"
                placeholder="请输入手机号"
                type="text"
                :clearable="false"
                :maxlength="11"
                @blur="validateField('contactPhone')"
              />
            </uni-forms-item>
            <uni-forms-item label="收货地址" name="contactAddress" required validate-trigger="blur">
              <uni-easyinput
                v-model="editForm.contactAddress"
                placeholder="请输入详细收货地址"
                type="textarea"
                :maxlength="200"
                :clearable="false"
                autoHeight
                @blur="validateField('contactAddress')"
              />
            </uni-forms-item>
          </uni-forms>
        </view>
        <view class="modal-footer">
          <button class="modal-btn cancel-btn" @click="closeEditModal">取消</button>
          <button class="modal-btn confirm-btn" @click="saveOrderInfo" :disabled="submitLoading">
            {{ submitLoading ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { onLoad, onUnload, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
import request from '@/utils/request';

// 订单商品项类型
interface OrderProduct {
  productId: string | number;
  productName: string;
  attrValue: string;
  sellingPrice: number;
  mainImageUrl: string;
  productNum: number;
}

// 订单数据接口类型
interface OrderItem {
  id: string | number;
  orderNumber: string;
  orderStatus: number;
  orderStatusStr: string;
  sellingPrice: number;
  createTime: string;
  orderItems: OrderProduct[];
  // 客户信息字段
  customerUserName?: string;
  customerUserPhonenumber?: string;
  customerUserAddress?: string;
}

// 编辑表单数据类型
interface EditForm {
  contactName: string;
  contactPhone: string;
  contactAddress: string;
}

// 页面状态
const currentTab = ref(0);
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);
const allDataLoaded = ref(false);

// 记录是否从下单成功跳转过来
const fromOrderSuccess = ref(false);

// 编辑弹窗相关状态
const editPopup = ref<any>(null);
const editFormRef = ref<any>(null);
const submitLoading = ref(false);
const currentEditOrder = ref<OrderItem | null>(null);
const editForm = ref<EditForm>({
  contactName: '',
  contactPhone: '',
  contactAddress: '',
});

// 表单验证规则
const formRules = {
  contactName: {
    rules: [
      {
        required: true,
        errorMessage: '请输入联系人姓名',
      },
      {
        minLength: 2,
        maxLength: 10,
        errorMessage: '姓名长度在2-10个字符之间',
      },
    ],
  },
  contactPhone: {
    rules: [
      {
        required: true,
        errorMessage: '请输入手机号',
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        errorMessage: '请输入正确的手机号格式',
      },
    ],
  },
  contactAddress: {
    rules: [
      {
        required: true,
        errorMessage: '请输入收货地址',
      },
      {
        minLength: 5,
        maxLength: 200,
        errorMessage: '地址长度在5-200个字符之间',
      },
    ],
  },
};

// 筛选标签
const filterTabs = ['全部', '待完善', '待确认', '待出货', '待结算', '已完成', '已取消'];

// 分页参数
const pageNum = ref(1);
const pageSize = ref(10);
const productName = ref('');

// 订单数据
const orders = ref<OrderItem[]>([]);

// 显示的订单列表（不再需要前端筛选，由接口筛选）
const filteredOrders = computed(() => {
  return orders.value;
});

// 获取订单列表
const getOrderList = async (isRefresh = false) => {
  if (loading.value || refreshing.value) return;

  if (isRefresh) {
    refreshing.value = true;
    pageNum.value = 1;
    hasMore.value = true;
    allDataLoaded.value = false;
  } else {
    loading.value = true;
  }

  try {
    // 根据选中的标签获取对应的订单状态
    const statusMap = [null, 1, 10, 20, 30, 60, 90]; // null表示全部，对应新的状态值
    const orderStatus = statusMap[currentTab.value];

    const params: any = {
      productName: productName.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    };

    // 如果不是"全部"标签，添加状态筛选
    if (orderStatus !== null) {
      params.orderStatus = orderStatus;
    }

    const response: any = await request({
      url: '/order/list',
      method: 'GET',
      data: params,
    });

    console.log('订单列表响应:', response);

    if (response.code === 200) {
      const newOrders = response.rows || [];
      const total = response.total || 0;

      if (isRefresh || pageNum.value === 1) {
        orders.value = newOrders;
      } else {
        orders.value = [...orders.value, ...newOrders];
      }

      // 根据总数量判断是否还有更多数据
      const currentTotal = orders.value.length;
      hasMore.value = currentTotal < total;
      allDataLoaded.value = !hasMore.value && currentTotal > 0;

      if (!isRefresh && hasMore.value) {
        pageNum.value++;
      }

      console.log(`当前已加载: ${currentTotal}，总计: ${total}，还有更多: ${hasMore.value}`);
    } else {
      uni.showToast({
        title: response.msg || '获取订单列表失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
    });
  } finally {
    loading.value = false;
    refreshing.value = false;

    if (isRefresh) {
      uni.stopPullDownRefresh();
    }
  }
};

// 切换标签
const switchTab = (index: number) => {
  currentTab.value = index;
  pageNum.value = 1;
  orders.value = [];
  hasMore.value = true;
  allDataLoaded.value = false;
  getOrderList(true);
};

// 获取状态文本（直接使用后端返回的orderStatusStr）
const getStatusText = (order: OrderItem) => {
  return order.orderStatusStr || '未知';
};

// 获取状态类型
const getStatusType = (orderStatus: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'warning', // 待完善 - 橙色警告
    10: 'primary', // 待确认 - 蓝色主色
    20: 'info', // 待出货 - 浅蓝色信息
    30: 'warning', // 待结算 - 橙色警告
    60: 'success', // 已完成 - 绿色成功
    90: 'error', // 已取消 - 红色错误
    91: 'error', // 已销毁 - 红色错误
  };
  return typeMap[orderStatus] || 'default';
};

// 查看订单详情
const viewOrderDetail = (order: OrderItem) => {
  // 构建商品列表信息
  const productsInfo = order.orderItems
    .map(
      (item, index) =>
        `商品${index + 1}：${item.productName}\n规格：${item.attrValue || '无'}\n价格：¥${(item.sellingPrice / 100).toFixed(2)}`
    )
    .join('\n\n');

  const customerInfo = order.customerUserName
    ? `\n\n收货信息：\n姓名：${order.customerUserName}\n电话：${order.customerUserPhonenumber || '无'}\n地址：${order.customerUserAddress || '无'}`
    : '\n\n收货信息：待完善';

  uni.showModal({
    title: '订单详情',
    content: `订单编号：${order.orderNumber}\n订单状态：${getStatusText(order)}\n下单时间：${order.createTime}\n订单总金额：¥${(order.sellingPrice / 100).toFixed(2)}\n\n${productsInfo}${customerInfo}`,
    showCancel: false,
    confirmText: '确定',
  });
};

// 完善订单信息
const editOrder = (order: OrderItem) => {
  currentEditOrder.value = order;

  // 根据订单中的客户信息初始化表单
  editForm.value = {
    contactName: order.customerUserName || '',
    contactPhone: order.customerUserPhonenumber || '',
    contactAddress: order.customerUserAddress || '',
  };

  console.log('初始化表单数据:', {
    orderId: order.id,
    formData: editForm.value,
    orderCustomerInfo: {
      name: order.customerUserName,
      phone: order.customerUserPhonenumber,
      address: order.customerUserAddress,
    },
  });

  // 显示弹窗
  editPopup.value?.open();

  // 等待弹窗渲染完成后重置表单验证状态
  nextTick(() => {
    // 重置表单验证状态，清除之前的验证错误
    editFormRef.value?.clearValidate();
  });
};

// 单个字段失焦验证
const validateField = (name: string) => {
  editFormRef.value?.validateField([name], (valid: boolean, errors: any) => {
    if (!valid) {
      console.log(`${name} 验证失败:`, errors);
    }
  });
};

// 关闭编辑弹窗
const closeEditModal = () => {
  editPopup.value?.close();
  currentEditOrder.value = null;

  // 清空表单数据
  editForm.value = {
    contactName: '',
    contactPhone: '',
    contactAddress: '',
  };

  // 等待下一帧后重置表单验证状态，确保表单组件已更新
  nextTick(() => {
    editFormRef.value?.clearValidate();
  });

  console.log('关闭编辑弹窗，表单已重置');
};

// 保存订单信息
const saveOrderInfo = async () => {
  if (!currentEditOrder.value) return;

  try {
    // 使用uni-forms进行表单验证
    await editFormRef.value.validate();
  } catch (errors: any) {
    // 验证失败，uni-forms会自动显示错误信息
    console.log('表单验证失败:', errors);
    return;
  }

  submitLoading.value = true;

  try {
    // 调用真实的更新订单信息接口
    const updateData = {
      id: currentEditOrder.value.id,
      customerUserName: editForm.value.contactName.trim(),
      customerUserPhonenumber: editForm.value.contactPhone.trim(),
      customerUserAddress: editForm.value.contactAddress.trim(),
    };

    const response: any = await request({
      url: '/order',
      method: 'PUT',
      data: updateData,
    });

    console.log('更新订单信息响应:', response);

    if (response.code === 200) {
      uni.showToast({
        title: '订单信息已更新',
        icon: 'success',
      });

      // 关闭弹窗
      closeEditModal();

      // 刷新订单列表
      await getOrderList(true);
    } else {
      throw new Error(response.msg || '更新失败');
    }
  } catch (error: any) {
    console.error('更新订单信息失败:', error);
    uni.showToast({
      title: error.message || '更新失败，请重试',
      icon: 'none',
    });
  } finally {
    submitLoading.value = false;
  }
};

// 取消订单
const cancelOrder = (order: OrderItem) => {
  uni.showModal({
    title: '取消订单',
    content: '确定要取消这个订单吗？',
    success: (res) => {
      if (res.confirm) {
        // 这里应该调用取消订单的接口
        uni.showToast({
          title: '功能开发中',
          icon: 'none',
        });
      }
    },
  });
};

// 确认收货
const confirmReceive = (order: OrderItem) => {
  uni.showModal({
    title: '确认收货',
    content: '确认已收到商品吗？',
    success: (res) => {
      if (res.confirm) {
        // 这里应该调用确认收货的接口
        uni.showToast({
          title: '功能开发中',
          icon: 'none',
        });
      }
    },
  });
};

// 评价订单
const reviewOrder = (order: OrderItem) => {
  uni.showToast({
    title: '评价功能开发中',
    icon: 'none',
  });
};

// 页面加载时获取参数
onLoad((options: any) => {
  if (options && options.fromOrderSuccess === 'true') {
    fromOrderSuccess.value = true;
    console.log('从下单成功页面跳转过来');
  }
});

// 监听页面卸载事件 - 强制跳转到个人中心
onUnload(() => {
  console.log('📱 订单页面卸载，强制跳转到个人中心');
  // 页面卸载时立即跳转到个人中心
  setTimeout(() => {
    uni.switchTab({
      url: '/pages/user/profile',
      fail: () => {
        uni.reLaunch({
          url: '/pages/user/profile',
        });
      },
    });
  }, 0);
});

// 下拉刷新
onPullDownRefresh(() => {
  console.log('下拉刷新');
  getOrderList(true);
});

// 上拉加载更多
onReachBottom(() => {
  console.log('触底加载更多');
  if (hasMore.value && !loading.value && !refreshing.value) {
    getOrderList(false);
  }
});

// 页面挂载完成
onMounted(async () => {
  // 初始加载订单列表
  await getOrderList(true);
});
</script>

<style scoped>
.container {
  background-color: #f8f8f8;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
    sans-serif;
}

/* 筛选标签样式优化 */
.filter-tabs {
  display: flex;
  background-color: #fff;
  padding: 16rpx 0;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.filter-tab {
  flex: 1;
  text-align: center;
  font-size: 26rpx;
  color: #888;
  padding: 16rpx 0;
  position: relative;
  font-weight: 400;
  transition: all 0.3s ease;
}

.filter-tab.active {
  color: #ff6600;
  font-weight: 500;
}

.filter-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 32rpx;
  height: 3rpx;
  background-color: #ff6600;
  border-radius: 2rpx;
}

/* 订单列表样式优化 */
.order-list {
  padding: 0 16rpx;
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  border: 1rpx solid #f0f0f0;
}

/* 订单头部优化 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.order-no {
  font-size: 22rpx;
  color: #333;
  font-weight: 400;
}

.order-time {
  font-size: 20rpx;
  color: #bbb;
  font-weight: 400;
}

/* 商品列表容器 */
.order-products {
  margin-bottom: 20rpx;
}

/* 订单内容区域优化 */
.order-content {
  display: flex;
  align-items: flex-start;
  padding-bottom: 20rpx;
}

.order-content.not-last {
  margin-bottom: 20rpx;
  border-bottom: 1rpx dashed #e8e8e8;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  border: 1rpx solid #f0f0f0;
  flex-shrink: 0;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  min-height: 160rpx;
}

.product-name {
  font-size: 26rpx;
  color: #333;
  font-weight: 400;
  line-height: 1.4;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-spec {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 12rpx;
  font-weight: 400;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.price {
  font-size: 26rpx;
  color: #ff6600;
  font-weight: 500;
}

.quantity {
  font-size: 22rpx;
  color: #999;
  font-weight: 400;
}

/* 订单底部优化 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16rpx;
  border-top: 1rpx solid #f5f5f5;
}

.total {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  border-radius: 16rpx;
  font-size: 22rpx;
  border: none;
  font-weight: 400;
  transition: all 0.3s ease;
}

.action-btn.edit {
  background-color: #ff6600;
  color: #fff;
}

.action-btn.cancel {
  background-color: #f5f5f5;
  color: #888;
}

.action-btn.confirm {
  background-color: #007aff;
  color: #fff;
}

.action-btn.review {
  background-color: #28a745;
  color: #fff;
}

/* 空状态样式优化 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 24rpx;
  opacity: 0.4;
}

.empty-text {
  font-size: 26rpx;
  color: #bbb;
  font-weight: 400;
}

/* 加载状态样式优化 */
.loading-state {
  display: flex;
  justify-content: center;
  padding: 40rpx 0;
}

.load-more-container {
  padding: 20rpx 0;
  text-align: center;
}

.all-loaded {
  padding: 30rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.all-loaded::before,
.all-loaded::after {
  content: '';
  flex: 1;
  height: 1rpx;
  background-color: #e8e8e8;
}

.all-loaded-text {
  font-size: 22rpx;
  color: #bbb;
  padding: 0 20rpx;
  background-color: #f8f8f8;
  font-weight: 400;
}

.no-more {
  padding: 20rpx 0;
}

.no-more-text {
  font-size: 22rpx;
  color: #bbb;
  font-weight: 400;
}

/* 编辑弹窗样式优化 */
.edit-modal {
  width: 600rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 24rpx 16rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
}

.close-btn {
  font-size: 36rpx;
  color: #bbb;
  width: 36rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 32rpx 24rpx;
}

.modal-footer {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
}

.modal-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  border: none;
  background: none;
  font-weight: 400;
}

.cancel-btn {
  color: #888;
  border-right: 1rpx solid #f0f0f0;
}

.confirm-btn {
  color: #ff6600;
  font-weight: 500;
}

.confirm-btn:disabled {
  color: #ddd;
}

/* 状态标签样式优化 */
:deep(.uni-tag) {
  font-size: 20rpx !important;
  padding: 4rpx 12rpx !important;
  border-radius: 10rpx !important;
  font-weight: 400 !important;
}

:deep(.uni-tag--warning) {
  background-color: #fff7e6 !important;
  color: #ff8c00 !important;
  border: 1rpx solid #ffd591 !important;
}

:deep(.uni-tag--primary) {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
  border: 1rpx solid #91d5ff !important;
}

:deep(.uni-tag--success) {
  background-color: #f6ffed !important;
  color: #52c41a !important;
  border: 1rpx solid #b7eb8f !important;
}

:deep(.uni-tag--error) {
  background-color: #fff2f0 !important;
  color: #ff4d4f !important;
  border: 1rpx solid #ffb3b3 !important;
}

:deep(.uni-tag--info) {
  background-color: #f0f5ff !important;
  color: #722ed1 !important;
  border: 1rpx solid #d3adf7 !important;
}
</style>
